<?php

namespace App\Service\Index;

use App\Constants\ErrorCode;
use App\Helpers\EventUtil;
use App\Model\CallBase;
use App\Model\Service\ConsumeService;
use App\Model\VideoCall;
use App\Service\CallBaseService;

/**
 * 挂断当前视频通话
 */
class HangupVideoService extends CallBaseService
{
    protected function RoVerifyList()
    {
        return [
            'chat_user_id' => 'required|int',
        ];
    }

    public function handle()
    {
        $userId = $this->getUserId();
        $chatUserId = $this->request->input('chat_user_id', 0);
        $isYellowHangup = $this->request->input('isYellowHangup', 0);
        if (!$chatUserId) return $this->setError(ErrorCode::PARAMETER_ERROR, '参数错误');

        //检测挂断权限
        $ret = ['result' => 1];
        $checkResult = $this->checkHangup($userId, $chatUserId, VideoCall::CALL_TYPE);
        if ($checkResult['ret'] != 0) {
            log_user_result($userId, "ChatUser:{$chatUserId}==RetError==" . json_encode($checkResult));
            return $checkResult;
        } elseif ($checkResult['return']) {
            $record = $checkResult['record'] ?? null;
            $ret['call_minutes'] = $record ? CallBase::getCallMinutes($record->call_time) : 0;
            log_user_result($userId, "ChatUser:{$chatUserId}==Return==CallId:{$record->id}==Minutes:{$ret['call_minutes']}");
            return $ret;
        }

        //挂断操作
        $record = $this->doHangup($record = $checkResult['record'], $isYellowHangup);

        //话单时长
        $ret['call_minutes'] = CallBase::getCallMinutes($record->call_time);
        log_user_result($userId, "ChatUser:{$chatUserId}==CallId:{$record->id}==CallTime:{$record->call_time}");
        return $ret;
    }

    /**
     * 挂断
     */
    protected function doHangup($callRecord = null, $isYellowHangup = 0)
    {
        //离开频道
        $agoraStatus = $this->request->input('agora_status', 0);
        $callRecord = CallBase::channelOutUpdate($callRecord, 1, $agoraStatus, $isYellowHangup);
        if (!$callRecord) return;
        //通话消费处理
        switch ($callRecord->from) {
                //新手福利
//            case CallBase::FROM_DAILY_FREE:
//                ConsumeService::settleCallForFree($callRecord, VideoCall::CALL_TYPE);
//                break;
//            case CallBase::FROM_INVITE_CALL:
//                (new ConsumeService)->settleCallForInvite($callRecord,VideoCall::CALL_TYPE);
//                break;
            case CallBase::FROM_DISCOUNT_CALL:
                ConsumeService::settleCallByDiscount($callRecord, VideoCall::CALL_TYPE);
                break;
            default:
                ConsumeService::settleCall($callRecord, VideoCall::CALL_TYPE);
                break;
        }
        //事件分发-每日任务
        EventUtil::dispatchHangup($callRecord, 'video');
        return $callRecord;
    }
}
